/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
const router = require('express').Router();
const _route = {
    index: require('./viewRoutes/index'),

    _render_: function (url, req, res, renderParam, routes, next) {
        let skip = true;
        if (routes.length > 1) { //目前我们支持二层的url结构
            try {
                let fun;
                if (routes.length == 2)
                    fun = _route['index'][routes[1]];
                else if (routes.length = 3)
                    fun = _route[routes[1]][routes[2]];
                if (fun != null) {
                    skip = false;
                    fun(renderParam.userData, req, res, function (data, permission, err) {
                        if (permission && permission > req.session.userData.status) {
                            url = 'mobile/noAccess';
                        }
                        if (err) {
                            next(err);
                        } else {
                            renderParam.data = data;
                            res.render(url, renderParam);
                        }
                    }, next);
                }
            } catch (e) {
            }
        }
        if (skip) {
            res.render(url, renderParam);
        }
    },
    _parseOpenId: function (openId, url, renderParam, routes, req, res, next) {
        let me = this;
        if (openId) {   //如果可以获取到openId的话，则获取用户信息
            req.session.openId = openId;
            global.tool.getUserInfo(openId, function (uData) {
                global.weChatUtil.getUserInfo(openId, function (weData) {
                    let userData = uData;
                    //从缓存中取barCode
                    req.session.userData = global.tool.extend(userData, weData);
                    console.log('user data:', userData);
                    renderParam.userData = req.session.userData;
                    me._render_(url, req, res, renderParam, routes, next);
                });
            });
        } else {
            res.send('<!DOCTYPE HTML><html><head><meta charset="UTF-8">' +
                '<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">' +
                '<meta http-equiv="X-UA-Compatible" content="IE=Edge">' +
                '<meta name="apple-mobile-web-app-capable" content="yes" />' +
                '<meta name="apple-mobile-web-app-status-bar-style" content="black" /></head>' +
                '<body ontouchstart>刷新成功，请关闭当前页面，重新打开！谢谢！</body></html>');
        }
    },
};

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
    console.log('view::' + req.path, Date.now());
    next();
});

router.get('/logout', function (req, res, next) {
    delete req.session.userData;
    res.redirect(global.config.contextPath + global.config.viewPrefix + '/');
});

/**
 * 实现路由转发
 */
router.use('/', function (req, res, next) {
    let language = req.headers["accept-language"] || 'zh-CN';
    if((language.split(",")[0]).toUpperCase().indexOf('TW')>-1){
        console.log('============================');
        req.setLocale("tw");
    }else{
        req.setLocale(language.substr(0,2));
    }
    console.log(req.locale,'***********************************');
    let url = "mobile" + (req.path.endsWith('/') ? req.path + "index" : req.path)
        , routes = req.path.split("/")
        , skip = true
        , renderParam = {
        path: url,
        queryData: req.query || {},
        session: req.session || {},
        cookie: req.cookies || {},
        data: {},
        userData: req.session.userData,//设置参数
        title: global.config.title
    };
    if (req.query.code) {
        console.log("page code:", req.query.code);
        global.weChatUtil.getOpenId(req.query.code, function (openId) {
            _route._parseOpenId(openId, url, renderParam, routes, req, res, next);
        });
    } else if (req.query.openId) {
        _route._parseOpenId(req.query.openId, url, renderParam, routes, req, res, next);
    } else {
        _route._render_(url, req, res, renderParam, routes, next);
    }

});

module.exports = router;
